<?php
/**
 * 案件管理控制器
 */
namespace app\lawcase\controller;

use app\base\BaseController;
use app\lawcase\model\Lawcase as LawcaseModel;
use app\lawcase\validate\LawcaseCheck;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\View;
use think\facade\Log;
use think\facade\Request;
use app\lawcase\model\CaseCause as CaseCauseModel;

class Lawcase extends BaseController
{
    protected $model;

    public function __construct()
    {
        parent::__construct();
        $this->model = new LawcaseModel();
    }

    /**
     * 案件列表
     * 若为 AJAX 请求，根据参数查询案件列表并返回数据；否则返回视图页面。
     */
    public function index()
    {
        if (Request::isAjax()) {
            $param = get_params();
            $where = [];
            
            // 数据权限控制：超级管理员可查看所有，其他人只能查看自己主办或管家的案件
            $uid = $this->uid;
            // 修改判断逻辑，使用uid==1或uid==8（冯铮）作为超级管理员判断条件
            $isSuperAdmin = $uid == 1 || $uid == 8 || $uid == 53 || $uid == 112;
            // 非超级管理员只能查看自己主办或管家的案件
            if (!$isSuperAdmin) {
                $where[] = ['main_lawyer|secondary_lawyer', '=', $uid];
            }
            
            $list = $this->model->getList($where, $param);
            return to_assign(0, '', $list);
        }
        
        // Get admin list for dropdowns
        $adminList = Db::name('admin')
        ->alias('a')
        ->join('department d', 'a.did = d.id')
        ->where('a.status', 1)
        ->where('d.title', 'in', ['浙江东星律师事务所', '浙江御和国诚律师事务所'])
        ->field('a.id, a.name')
        ->group('a.id')
        ->select();

        $secondaryLawyerList = Db::name('admin')
            ->alias('a')
            ->join('department d', 'a.did = d.id')
            ->where('a.status', 1)
            ->where('d.title', '法务中心')
            ->field('a.id, a.name')
            ->group('a.id')
            ->select();
        return view('', [
            'adminList' => $adminList,
            'secondaryLawyerList' => $secondaryLawyerList,
            'case_status' => \app\lawcase\model\Lawcase::$statusMap
        ]);
    }

    /**
     * 添加案件
     * 若为 AJAX 请求，验证并保存案件信息；否则为添加页面设置初始值并返回视图页面。
     */
    public function add()
    {
        if (request()->isAjax()) {
            $param = get_params();
            // 转换日期格式
            if (!empty($param['session_time'])) {
                $param['session_time'] = strtotime($param['session_time']);
            }
            
            //生成案件编号
            $param['case_code'] = $this->generateCaseCode($param['case_type']);
            // 调用模型层处理添加逻辑
            $this->model->addCase($param);
        } else {
            // 获取案由列表
            $case_causes = Db::name('case_cause')->where('delete_time', 0)->select();
            
            // 获取律师列表
            $adminList = Db::name('admin')
                ->alias('a')
                ->join('department d', 'a.did = d.id')
                ->where('a.status', 1)
                ->where('d.title', 'in', ['浙江东星律师事务所', '浙江御和国诚律师事务所'])
                ->field('a.id, a.name')
                ->group('a.id')
                ->select();
                
            // 获取管家列表
            $secondaryLawyerList = Db::name('admin')
                ->alias('a')
                ->join('department d', 'a.did = d.id')
                ->where('a.status', 1)
                ->where('d.title', '法务中心')
                ->field('a.id, a.name')
                ->group('a.id')
                ->select();
                
            // 使用模型中的静态属性设置变量
            $case_types = \app\lawcase\model\Lawcase::$caseTypeMap;
            $case_stage = \app\lawcase\model\Lawcase::$stageMap;
            $case_status = \app\lawcase\model\Lawcase::$statusMap;
            
            return view('', [
                'id' => 0,
                'adminList' => $adminList,
                'secondaryLawyerList' => $secondaryLawyerList,
                'case_types' => $case_types,
                'case_stage' => $case_stage,
                'case_status' => $case_status,
                'case_causes' => $case_causes
            ]);
        }
    }

    /**
     * 编辑案件
     * 若为 AJAX 请求，验证并更新案件信息；否则获取案件详情并返回视图页面。     
     * */
    public function edit()
    {
        if (request()->isAjax()) {
            $param = get_params();
            // 转换日期格式
            if (!empty($param['session_time'])) {
                $param['session_time'] = strtotime($param['session_time']);
            }
            // 调用模型层处理更新逻辑
            $this->model->editCase($param);
        }
        $id = input('id', 0);
        $detail = $this->model->getCase($id);
        if ($detail['code'] !== 0) {
            return to_assign(1, $detail['msg']);
        }
        // 获取案由列表
        $case_causes = Db::name('case_cause')->where('delete_time', 0)->select();
        // 获取管家列表
        $secondaryLawyerList = Db::name('admin')
            ->alias('a')
            ->join('department d', 'a.did = d.id')
            ->where('a.status', 1)
            ->where('d.title', '法务中心')
            ->field('a.id, a.name')
            ->group('a.id')
            ->select();

        // 使用模型中的静态属性设置变量
        $case_types = \app\lawcase\model\Lawcase::$caseTypeMap;
        $case_stage = \app\lawcase\model\Lawcase::$stageMap;
        $case_status = \app\lawcase\model\Lawcase::$statusMap;
        
        View::assign([
            'detail' => $detail['data'], 
            'id' => $id,
            'case_types' => $case_types,
            'case_stage' => $case_stage,
            'case_status' => $case_status,
            'case_causes' => $case_causes,
            'secondaryLawyerList' => $secondaryLawyerList
        ]);
        return view('add');
    }

    /**
     * 删除案件
     * 根据案件 ID 删除案件信息。
     */
    public function delete()
    {
        $id = get_params("id");
        return $this->model->removeCase($id);
    }

    /**
     * 案件详情
     */
    public function view()
    {
        $id = (int)input('id', 0);  // 添加类型转换
        $detail = $this->model->getCase($id);
        if ($detail['code'] !== 0) {
            return to_assign(1, $detail['msg']);
        }
        View::assign(['detail' => $detail['data'],'id' => $id]);
        return view();
    }

    /**
     * 生成案件编号
     * 
     * @return string
     */
    protected function generateCaseCode($case_type)
    {
        // 生成案件编号的逻辑
        // 案号规则：年份+类型+序号
        // 例如：根据当前日期生成案件编号前缀，然后加上随机数
        $prefix = date('Y');
        //获取$case_type的第一个字，例如：民、刑、商、行政
        $case_type_prefix = mb_substr($case_type, 0, 1, 'UTF-8');
        $random = date('m').rand(1000, 9999);
        return $prefix . '（' .$case_type_prefix .'）'. $random;
    }
}
